import * as order from '@/api/order'
const state = {
  orderDetail: '',
  // 用户订单数据
  userOrderList: [],
  // 根据条件的不同展示不同的订单列表：全部订单，未完成订单，已完成订单，都由这个属性展示
  showOrderList: []
}

const mutations = {
  SET_ORDERDETAIL: (state, orderDetail) => {
    state.orderDetail = orderDetail
  },

  // 保存用户订单数据
  SET_USERORDERLIST: (state, userOrderList) => {
    state.userOrderList = userOrderList
  },
  SET_SHOWORDERLIST: (state, orderList) => {
    state.showOrderList = orderList
  }

}

const actions = {
  getOrderDetailById({ commit, state }, oid) {
    return new Promise((resolve, reject) => {
      order.getOrderById(oid).then(res => {
        commit('SET_ORDERDETAIL', res.object)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 根据传入的payload.type对orderList进行分类然后展示
  setShowOrderList({ commit, state }, type) {
    return new Promise((resolve, reject) => {
      let arr = []

      if (type === '1') {
        // 全部订单
        commit('SET_SHOWORDERLIST', state.userOrderList)
      } else if (type === '2') {
        // 未支付订单
        arr = state.userOrderList.filter(element => {
          return element.status === 0
        })
        commit('SET_SHOWORDERLIST', arr)
      } else if (type === '3') {
        // 待收货订单
        state.userOrderList.forEach(element => {
          if (element.status === 1 || element.status === 2) {
            arr.push(element)
          }
        })
        commit('SET_SHOWORDERLIST', arr)
      } else if (type === '4') {
        // 已完成订单
        state.userOrderList.forEach(element => {
          if (element.status === 4) {
            arr.push(element)
          }
        })
        commit('SET_SHOWORDERLIST', arr)
      } else if (type === '5') {
        // 取消的订单
        state.userOrderList.forEach(element => {
          if (element.status === 5 || element.status === 3) {
            arr.push(element)
          }
        })
        commit('SET_SHOWORDERLIST', arr)
      } else {
        reject('传入参数不正确')
      }
      resolve()
    })
  },

  // 展示搜索框搜索的相关订单
  // setShowOrderList2({ commit, state }, payload) {
  //   return new Promise((resolve, reject) => {
  //     commit('SET_SHOWORDERLIST', payload.arr)
  //   })
  // },

  // 获取用户订单列表
  getUserOrderList({ commit, state }, uid) {
    return new Promise((resolve, reject) => {
      order.getOrderList(uid).then(res => {
        commit('SET_USERORDERLIST', res.object)
        commit('SET_SHOWORDERLIST', res.object)
        resolve(res)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
